package com.imchen.cms.cmscommon.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

/**
 * @author imchen
 * @create: 2019-01-24 16:26
 **/
public class StringUtil {

        private static Logger logger = LoggerFactory.getLogger(StringUtil.class);
        /**
         * 过滤非汉字的utf8的字符（包括emoji）
         *
         * @param text 原字符串
         * @return 过滤后的字符串
         */
        public static String filterOffUtf8Mb4(String text) {
            byte[] bytes = new byte[0];
            try {
                bytes = text.getBytes("utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("filterOffUtf8Mb4 text to bytes, UnsupportedEncodingException: {}", e);
            }
            ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
            int i = 0;
            while (i < bytes.length) {
                short b = bytes[i];
                if (b > 0) {
                    buffer.put(bytes[i++]);
                    continue;
                }
                b += 256; //去掉符号位
                if (((b >> 5) ^ 0x06) == 0) {
                    buffer.put(bytes, i, 2);
                    i += 2;
                    System.out.println("2");
                } else if (((b >> 4) ^ 0x0E) == 0) {
                    System.out.println("3");
                    buffer.put(bytes, i, 3);
                    i += 3;
                } else if (((b >> 3) ^ 0x1E) == 0) {
                    i += 4;
                    System.out.println("4");
                } else if (((b >> 2) ^ 0xBE) == 0) {
                    i += 5;
                    System.out.println("5");
                } else {
                    i += 6;
                    System.out.println("6");
                }
            }
            buffer.flip();
            try {
                return new String(buffer.array(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("filterOffUtf8Mb4 result, UnsupportedEncodingException: {}", e);
                return "";
            }
        }
}